#! /usr/bin/env python3
# -*- encoding:utf-8 -*-

import logging
import asyncio
import json
from aiohttp import web
from requesthandle import add_routes, add_static
import sql
from helper.config import configs
import os
from jinja2 import Environment, FileSystemLoader
import time
import datetime
logging.basicConfig(level=logging.INFO)


async def logger_factory(app, handler):
    async def logger(request):
        logging.info('Request: %s %s' % (request.method, request.path))
        return (await handler(request))

    return logger


async def response_factory(app, handler):
    async def response(request):
        r = await handler(request)
        if isinstance(r, web.StreamResponse):
            return r
        if isinstance(r, bytes):
            resp = web.Response(body=r)
            resp.content_type = 'application/octet-stream'
            return resp
        if isinstance(r, str):
            resp = web.Response(body=r.encode('utf-8'))
            resp.content_type = 'text/html;charset=utf-8'
            return resp
        if isinstance(r, dict):
            template = r.get('__template__')
            if template is None:
                resp = web.Response(
                    body=json.dumps(
                        r, ensure_ascii=False, default=lambda o: o.__dict__)
                    .encode('utf-8'))
                resp.content_type = 'application/json;charset=utf-8'
                return resp
            else:
                resp = web.Response(body=app['__templating__'].get_template(
                    template).render(**r).encode('utf-8'))
                resp.content_type = 'text/html;charset=utf-8'
                return resp
        resp = web.Response(body=str(r).encode('utf-8'))
        resp.content_type = 'text/plain;charset=utf-8'
        return resp

    return response


# 初始化模板页面引擎
def init_jinja2(app, **kw):
    logging.info("初始化jinja...")
    option = dict(
        autoescape=kw.get('autoescape', True),
        block_start_string=kw.get('block_start_string', '{%'),
        block_end_string=kw.get('block_end_string', '%}'),
        variable_start_string=kw.get('variable_start_string', '{{'),
        variable_end_string=kw.get('variable_end_string', '}}'),
        auto_reload=kw.get('auto_reload', True))
    path = kw.get("path", None)
    if path is None:
        path = os.path.join(
            os.path.dirname(os.path.abspath(__file__)), 'template')
    logging.info("jinja的模板路径为:%s" % path)
    env = Environment(loader=FileSystemLoader(path), **option)
    filters = kw.get('filters', None)
    if filters is not None:
        for name, func in filters.items():
            env.filters[name] = func
    app['__templating__'] = env


def datetime_filter(t):
    delta = int(time.time() - t)
    if delta < 60:
        return u'1分钟前'
    if delta < 3600:
        return u'%s分钟前' % (delta // 60)
    if delta < 86400:
        return u'%s小时前' % (delta // 3600)
    if delta < 604800:
        return u'%s天前' % (delta // 86400)
    dt = datetime.fromtimestamp(t)
    return u'%s年%s月%s日' % (dt.year, dt.month, dt.day)


async def init(loop):
    app = web.Application(
        loop=loop, middlewares=[logger_factory, response_factory])
    init_jinja2(app, filters=dict(datetime=datetime_filter))
    # app.router.add_route('GET', '/', index)
    await sql.create_pool(
        user=configs['db']['user'],
        password=configs['db']['password'],
        db=configs['db']['database'],
        loop=loop)
    add_routes(app, 'handlers')
    add_static(app)
    srv = await loop.create_server(app.make_handler(), '127.0.0.1', 9010)
    logging.info("server started at http://127.0.0.1:9010")
    return srv


loop = asyncio.get_event_loop()
loop.run_until_complete(init(loop))
loop.run_forever()
